/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package net.worlds.object;

import net.worlds.WorldsException;
import net.worlds.PhysicsController;
import net.worlds.PropChangeHandler;


public class FixedAngularVelocity extends GameObject{
    private boolean running;
    private Part part;
    private float vel = -1;
    private int timer = 0;
    private PhysicsController controller;
    public FixedAngularVelocity() throws WorldsException
    {
        super("FixedAngularVelocity");
        addPropChangeHandler("Parent", new PropChangeHandler()
        {
            @Override
            public void handle(Object oldValue, Object value) throws WorldsException {
                onParentChanged((GameObject) oldValue, (GameObject) value);
                if(value instanceof Part)
                {
                    if(oldValue instanceof Part)
                        stop();
                    if(part != null)
                        start((Part)value);
                }
            }
        });
        addPropChangeHandler("Velocity", new PropChangeHandler()
        {
            @Override
            public void handle(Object oldValue, Object value) throws WorldsException {
                vel = (Float) value;
            }
        });
        //x_;
    }
    @Override
    public void addToWorld() throws WorldsException
    {
        super.addToWorld();
        if(getParent() instanceof Part)
            start((Part)getParent());
    }
    private void start(Part p)
    {
        part = p;
        part.getBody().wakeUp();
        if(!part.hasController(controller))
        {
            controller = new PhysicsController()
            {

                @Override
                public void run() {
                    part.getBody().wakeUp();
                    if(vel != -1 && part != null)
                    {
                        part.getBody().setAngularVelocity(vel);
                    }
                }

            };
            part.addController(controller);
        }
    }
    private void stop()
    {
        if(part != null)
        {
            part.removeController(controller);
        }
    }
    @Override
    public void destructor() throws WorldsException
    {
        super.destructor();
        stop();
    }
}
